package vn.personal.anhht.bloback12.block;

import java.lang.reflect.Method;
import java.util.ArrayList;

import vn.personal.anhht.bloback12.activity.NotificationActivity;
import vn.personal.anhht.bloback12.activity.R;
import vn.personal.anhht.bloback12.database.CallBlockDatabaseAdapter;
import vn.personal.anhht.bloback12.database.CallBlockDatabaseCallsBlockAdapter;
import vn.personal.anhht.bloback12.util.Constants;
import vn.personal.anhht.bloback12.util.UtilMethods;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.android.internal.telephony.ITelephony;

public class BlockIncomingCall extends BroadcastReceiver {
    Context context = null;
    private static final String TAG = "BlockIncomingCall";
    private ITelephony telephonyService;
    public static String msg = "";
    boolean ringring = false;
    boolean isHavaABlockCall = false;
    Resources res;
    private String phone;
    @Override
    public void onReceive(Context context, Intent intent) {

        res = context.getResources();
        this.context = context;
        boolean turnBlock = context.getSharedPreferences(
                Constants.SETTINGS_SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE).getBoolean(
                res.getString(R.string.call_pref_turn_key), false);
        if (turnBlock) {
            TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            Bundle bundle = intent.getExtras();
            String phone = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
            String state = bundle.getString(TelephonyManager.EXTRA_STATE);
            String typeBlock = context.getSharedPreferences(
                    Constants.SETTINGS_SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE).getString(
                    res.getString(R.string.call_pref_mode_block_key), "");
            String typeInform = context.getSharedPreferences(
                    Constants.SETTINGS_SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE).getString(
                    res.getString(R.string.call_pref_mode_inform_key), "");
            String phoneState = context.getSharedPreferences(
                    Constants.SETTINGS_SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE).getString(
                    res.getString(R.string.call_pref_phone_state_key), "");
            
            if ("RINGING".equals(state)) {
                if ("blacklist".equals(typeBlock)) {
                    if (isBlockedNumber(phone.trim())) {
                        isHavaABlockCall = true;
                        try {
                            AudioManager audioManager = (AudioManager) this.context
                                    .getSystemService(Context.AUDIO_SERVICE);
                            audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
                            Method m;
                            m = Class.forName(telephony.getClass().getName()).getDeclaredMethod("getITelephony");
                            m.setAccessible(true);
                            telephonyService = (ITelephony) m.invoke(telephony);
                            telephonyService.endCall();
                            audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }
                        if ("showcall".equals(typeInform)) {
                            sendNotification(phone);
                        }
                        if ("endcallsms".equals(phoneState)) {
                            autoReply(phone);
                        }
                    }
                }if("whitelist".equals(typeBlock)){
                    Log.e("dafs", "Vo whilelist");
                    if(isNotWhiteNumber(phone.trim())){
                        isHavaABlockCall = true;
                        try {
                            AudioManager audioManager = (AudioManager) this.context
                                    .getSystemService(Context.AUDIO_SERVICE);
                            audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
                            Method m;
                            m = Class.forName(telephony.getClass().getName()).getDeclaredMethod("getITelephony");
                            m.setAccessible(true);
                            telephonyService = (ITelephony) m.invoke(telephony);
                            telephonyService.endCall();
                            audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }
                        if ("showcall".equals(typeInform)) {
                            sendNotification(phone);
                        }
                        if ("endcallsms".equals(phoneState)) {
                            autoReply(phone);
                        }
                    }
                }else {
                    isHavaABlockCall = true;
                    try {
                        AudioManager audioManager = (AudioManager) this.context
                            .getSystemService(Context.AUDIO_SERVICE);
                        audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
                        Method m;
                        m = Class.forName(telephony.getClass().getName())
                                .getDeclaredMethod("getITelephony");
                        m.setAccessible(true);
                        telephonyService = (ITelephony) m.invoke(telephony);
                        // telephonyService.silenceRinger();
                        telephonyService.endCall();
                        audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                    if ("showcall".equals(typeInform)) {
                        sendNotification(phone);
                    }
                    if ("endcallsms".equals(phoneState)) {
                        autoReply(phone);
                    }
                }
                this.phone = phone;
                Handler myHandler = new Handler();
                myHandler.postDelayed(mMyRunnable, 2000);
            }
        }// End block
    }
    
    private Runnable mMyRunnable = new Runnable()
    {
        @Override
        public void run()
        {
            deleteLastCall(phone);
        }
     };
    
    public boolean isBlockedNumber(String phone) {
        boolean isBlock = false;
        String nPhone = "";
        if (phone.contains("+84")) {
            nPhone = "0" + phone.substring(3);
        } else {
            nPhone = phone;
        }
        CallBlockDatabaseAdapter databaseAdapter = new CallBlockDatabaseAdapter(
                context);
        databaseAdapter.open();
        Cursor cr = databaseAdapter.selectBlackListByPhone(nPhone);
        String num = "";
        int isBlockCall;
        if (cr.moveToFirst()) {
            do {
                // phone.equals(cr.getString(cr.getColumnIndex(databaseAdapter.KEY_PHONE)))
                num = cr.getString(cr
                        .getColumnIndex(CallBlockDatabaseAdapter.KEY_PHONE));
                isBlockCall = cr
                        .getInt(cr
                                .getColumnIndex(CallBlockDatabaseAdapter.KEY_IS_BLOCK_CALL));
                if (num != null) {
                    if (num.equals(phone)) {
                        if (isBlockCall == 1) {
                            isBlock = true;
                            break;
                        }
                    }
                } else {
                    Log.e(TAG, "Null");
                }
            } while (cr.moveToNext());

        }

        cr.close();
        databaseAdapter.close();
        return isBlock;
    }
    public boolean isNotWhiteNumber(String phone) {
        boolean isBlock = true;
        String nPhone = "";
        if (phone.contains("+84")) {
            nPhone = "0" + phone.substring(3);
        } else {
            nPhone = phone;
        }
        CallBlockDatabaseAdapter databaseAdapter = new CallBlockDatabaseAdapter(
                context);
        databaseAdapter.open();
        Cursor cr = databaseAdapter.selectWhiteListByPhone(nPhone);
        String num = "";
        int isBlockCall;
        if (cr.moveToFirst()) {
            do {
                // phone.equals(cr.getString(cr.getColumnIndex(databaseAdapter.KEY_PHONE)))
                num = cr.getString(cr
                        .getColumnIndex(CallBlockDatabaseAdapter.KEY_PHONE));
                isBlockCall = cr
                        .getInt(cr
                                .getColumnIndex(CallBlockDatabaseAdapter.KEY_IS_WHITE_LIST));
                if (num != null) {
                    if (num.equals(phone)) {
                        if(isBlockCall == 1){
                            isBlock = false;
                            break;
                        }
                    }
                } else {
                    Log.e(TAG, "Null");
                }
            } while (cr.moveToNext());

        }

        cr.close();
        databaseAdapter.close();
        return isBlock;
    }
    
    public void autoReply(String phone) {
        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage(phone, null,
                "Huynh Tuan Anh ykujujujujujujujujujujujuj", null, null);
    }
    
    public void sendNotification(String phone) {
        Intent intentNotify = new Intent(context, NotificationActivity.class);
        intentNotify.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intentNotify.putExtra("NOTIFICATION_HEADER",
                res.getString(R.string.not_call_header));
        intentNotify.putExtra("NOTIFICATION_TITLE",
                res.getString(R.string.not_call_title));
        intentNotify.putExtra("NOTIFICATION_MESSAGE",
                res.getString(R.string.not_call_msg) + " [" + phone + "]");
        context.startActivity(intentNotify);
    }

    public boolean deleteLastCall(String phone) {
        Log.e("BlockIncomingCall", "deleteLastCall");
        boolean isDeleted = false;
        android.database.Cursor c = context.getContentResolver().query(
                android.provider.CallLog.Calls.CONTENT_URI, null, null, null,
                android.provider.CallLog.Calls.DATE + " DESC");
        ArrayList<String> callRecordsList = new ArrayList<String>();
        // Retrieve the column-indexes of phoneNumber, date and call type
        Cursor cursor = c;
        if (cursor.moveToFirst()) {
            while (!cursor.isAfterLast()) {
                String row_id = loadCallRecord(cursor); // Load attributes of last call
                callRecordsList.add(row_id);
                cursor.moveToNext();
            }
        }
        cursor.close();
        if (callRecordsList.size() > 0) {
            int deletedRows = context.getContentResolver().delete(
                    android.provider.CallLog.Calls.CONTENT_URI,
                    "_ID=" + callRecordsList.get(0), null);
            if (deletedRows > 0)
                isDeleted = true;
            else
                isDeleted = false;
            Log.i("Row Deleted status:", " " + isDeleted);
        }
        if (isHavaABlockCall) {
            isHavaABlockCall = false;
            String[] strFields = {android.provider.ContactsContract.PhoneLookup.DISPLAY_NAME };
            Cursor callCursor = context.getContentResolver()
                    .query(Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone)),
                            strFields, null, null, null);
            String mynumber = null;
            String mydate = null;
            String myname = null;
            int mytype = 3;
            mynumber = phone;
            mydate = UtilMethods.getCurrentDay();
            
            if (callCursor.isFirst()) {
                int indexOfCachedName = callCursor
                        .getColumnIndex(PhoneLookup.DISPLAY_NAME);
                myname = callCursor.getString(indexOfCachedName);
                mytype = 3;
                callCursor.close();
            }
            CallBlockDatabaseCallsBlockAdapter callsBlock = new CallBlockDatabaseCallsBlockAdapter(
                    context);
            callsBlock.open();
            callsBlock.addCallsBlock(mynumber, mydate, myname, mytype);
            callsBlock.close();
        }
        return isDeleted;
    }

    private String loadCallRecord(Cursor cursor) {
        //CallRecord contactData = new CallRecord();
        String lo_row_id = null;
        String[] ColumnNames = cursor.getColumnNames();
        for (int intLoop = 0; intLoop < ColumnNames.length; intLoop++) {
            // Load id of Last call
            if (android.provider.CallLog.Calls._ID
                    .compareTo(ColumnNames[intLoop]) == 0){
                lo_row_id = cursor.getString(intLoop);
                break;
            }
                
        }
        return lo_row_id;
    }
}
